package com.example.dryyzx.controller;

import com.example.dryyzx.dao.BedMapper;
import com.example.dryyzx.dao.BedRecordMapper;
import com.example.dryyzx.dao.CustomerMapper;
import com.example.dryyzx.encapsulation.CheckbedPageEncapsulation;
import com.example.dryyzx.encapsulation.CheckbedPageEncapsulation2;
import com.example.dryyzx.encapsulation.ChooseBedPageEncapsulation;
import com.example.dryyzx.encapsulation.DetailList;
import com.example.dryyzx.entity.Bed;
import com.example.dryyzx.entity.BedRecord;
import com.example.dryyzx.entity.Customer;
import com.example.dryyzx.entity.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Controller
public class BedController {

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private BedRecordMapper bedRecordMapper;

    private static boolean isNumeric(String str) {
        return str.matches("-?\\d+(\\.\\d+)?");  //match a number with optional '-' and decimal.
    }

    @RequestMapping(value = "choose_bed_page/find_customer",method = RequestMethod.POST)
    public @ResponseBody
    String searchCustomer(String search_key)throws ParseException {
        Customer customer = new Customer();
        if(isNumeric(search_key)){
            int customer_id=Integer.valueOf(search_key).intValue();
            customer = customerMapper.selectByPrimaryKey1(customer_id);
        }
        else{
            String archivesId=search_key;
            customer = customerMapper.selectByArchivesId(archivesId);
        }
        if(customer ==null)
            return new JsonResult(false, "找不到老人").toString();
        if(customer.getState().equals("已退住"))
            return new JsonResult(false, "该老人已退住").toString();

        Bed bed =new Bed();
        bed = bedMapper.selectByPrimaryKey(customer.getBedId());
        if(bed ==null)
            return new JsonResult(false, "找不到床位").toString();
        if(bed.getIsOccupied()==false)
            return new JsonResult(false, "该床位无人使用").toString();

        ChooseBedPageEncapsulation total_data = new ChooseBedPageEncapsulation();
        total_data.id=customer.getId();
        total_data.name=customer.getName();
        total_data.building_number=bed.getPosition();
        total_data.room_number=bed.getRoomNumber();
        total_data.bed_number=bed.getBedNumber();

        if(total_data==null )
            return new JsonResult(false, "无法返回数据").toString();
        return new JsonResult(true, total_data).toString();
    }

    @RequestMapping(value = "choose_bed_page/change_bed",method = RequestMethod.POST)
    public @ResponseBody
    String changeBed(int id, String bed_number, String room_number, String building_number){
        Bed targetBed = bedMapper.selectByBed_number(bed_number);
        if(targetBed==null)
            return new JsonResult(false, "找不到床位").toString();
        if(!Objects.equals(room_number, "") && !targetBed.getRoomNumber().equals(room_number))
            return new JsonResult(false, "房间号输入错误").toString();
        if(!Objects.equals(building_number, "") && !targetBed.getPosition().equals(building_number))
            return new JsonResult(false, "建筑输入错误").toString();
        if(targetBed.getIsOccupied())
            return new JsonResult(false, "该床位已经被占用").toString();

        Customer customer = customerMapper.selectByPrimaryKey1(id);
        if(customer==null)
            return new JsonResult(false, "找不到老人").toString();
        if(customer.getState().equals("已退住"))
            return new JsonResult(false, "该老人已退住").toString();

        Bed bed = bedMapper.selectByPrimaryKey(customer.getBedId());
        if(bed==null)
            return new JsonResult(false, "找不到老人原本的床位").toString();
        if(!bed.getIsOccupied())
            return new JsonResult(false, "老人原本的床位未被占用").toString();

        BedRecord bedRecord = bedRecordMapper.selectByBed_idAndCustomer_id(bed.getId(),customer.getId());
        if(bedRecord==null)
            return new JsonResult(false, "找不到老人原本的床位记录").toString();

        Date date = new Date();
        customer.setBedId(targetBed.getId());
        int update1 = customerMapper.updateByPrimaryKeySelective(customer);
        targetBed.setIsOccupied(true);
        int update2 = bedMapper.updateByPrimaryKeySelective(targetBed);
        bed.setIsOccupied(false);
        int update3 = bedMapper.updateByPrimaryKeySelective(bed);
        bedRecord.setLeavingTime(date);
        bedRecord.setEnable(false);
        int update4 = bedRecordMapper.updateByPrimaryKeySelective(bedRecord);
        BedRecord newBedRecord = new BedRecord();
        newBedRecord.setBedId(targetBed.getId());
        newBedRecord.setCustomerId(customer.getId());
        newBedRecord.setOccupiedTime(date);
        newBedRecord.setEnable(true);
        int insert = bedRecordMapper.insertSelective(newBedRecord);

        if(update1==0||update2==0||update3==0||update4==0||insert==0)
            return new JsonResult(false, "更新老人床位失败").toString();
        return new JsonResult(true, update1).toString();
    }

    @RequestMapping(value = "choose_bed_page/exchange_bed",method = RequestMethod.POST)
    public @ResponseBody
    String exchangeBed(int id1, int id2){
        if(id1==id2)
            return new JsonResult(false, "不能交换同一个老人的床位").toString();

        Customer customer1 = customerMapper.selectByPrimaryKey1(id1);
        if(customer1==null)
            return new JsonResult(false, "找不到前一个老人").toString();
        if(customer1.getState().equals("已退住"))
            return new JsonResult(false, "前一个老人已退住").toString();

        Customer customer2 = customerMapper.selectByPrimaryKey1(id2);
        if(customer2==null)
            return new JsonResult(false, "找不到后一个老人").toString();
        if(customer2.getState().equals("已退住"))
            return new JsonResult(false, "后一个老人已退住").toString();

        Bed bed1 = bedMapper.selectByPrimaryKey(customer1.getBedId());
        if(bed1==null)
            return new JsonResult(false, "找不到前一个老人床位").toString();
        if(!bed1.getIsOccupied())
            return new JsonResult(false, "前一个老人床位未被占用").toString();

        Bed bed2 = bedMapper.selectByPrimaryKey(customer2.getBedId());
        if(bed2==null)
            return new JsonResult(false, "找不到后一个老人床位").toString();
        if(!bed2.getIsOccupied())
            return new JsonResult(false, "后一个老人床位未被占用").toString();

        BedRecord bedRecord1 = bedRecordMapper.selectByBed_idAndCustomer_id(bed1.getId(),customer1.getId());
        if(bedRecord1==null)
            return new JsonResult(false, "找不到前一个老人原本的床位记录").toString();

        BedRecord bedRecord2 = bedRecordMapper.selectByBed_idAndCustomer_id(bed2.getId(),customer2.getId());
        if(bedRecord2==null)
            return new JsonResult(false, "找不到后一个老人原本的床位记录").toString();

        Date date = new Date();
        customer1.setBedId(bed2.getId());
        int update1 = customerMapper.updateByPrimaryKeySelective(customer1);
        customer2.setBedId(bed1.getId());
        int update2 = customerMapper.updateByPrimaryKeySelective(customer2);
        bedRecord1.setLeavingTime(date);
        bedRecord1.setEnable(false);
        int update3 = bedRecordMapper.updateByPrimaryKeySelective(bedRecord1);
        bedRecord2.setLeavingTime(date);
        bedRecord2.setEnable(false);
        int update4 = bedRecordMapper.updateByPrimaryKeySelective(bedRecord2);
        BedRecord newBedRecord1 = new BedRecord();
        newBedRecord1.setBedId(bed2.getId());
        newBedRecord1.setCustomerId(customer1.getId());
        newBedRecord1.setOccupiedTime(date);
        newBedRecord1.setEnable(true);
        int insert1 = bedRecordMapper.insertSelective(newBedRecord1);
        BedRecord newBedRecord2 = new BedRecord();
        newBedRecord2.setBedId(bed1.getId());
        newBedRecord2.setCustomerId(customer2.getId());
        newBedRecord2.setOccupiedTime(date);
        newBedRecord2.setEnable(true);
        int insert2 = bedRecordMapper.insertSelective(newBedRecord2);

        if(update1==0||update2==0||update3==0||update4==0||insert1==0||insert2==0)
            return new JsonResult(false, "交换老人床位失败").toString();
        return new JsonResult(true, update1).toString();
    }

    public @ResponseBody
    List<Customer> search_customer_by_bed(List<Bed> bed) {
        int i;
        List<Customer> customer = new ArrayList<>();
        Customer customertmp = null;
        for (i = 0; i < bed.size(); i++) {
            customertmp = customerMapper.selectByBedId(bed.get(i).getId());
            if(customertmp==null)
                customer.add(i,new Customer());
            else
                customer.add(i, customertmp);
        }
        return customer;
    }

    public @ResponseBody
    List<BedRecord> search_bed_record_by_bed_customer(List<Bed> bed,List<Customer> customer) {
        int i;
        List<BedRecord> bedRecord = new ArrayList<BedRecord>();
        BedRecord bedRecordtmp = null;
        for (i = 0; i < bed.size(); i++) {
            bedRecordtmp = bedRecordMapper.selectByBed_idAndCustomer_id(bed.get(i).getId(),customer.get(i).getId());
            if(bedRecordtmp==null)
                bedRecord.add(i,new BedRecord());
            else
                bedRecord.add(i, bedRecordtmp);
        }
        return bedRecord;
    }

    List<CheckbedPageEncapsulation> getEncapsulation(List<Bed> bed,List<Customer> customer,List<BedRecord> bedRecord,int limit){
        List<CheckbedPageEncapsulation> encapsulation = new ArrayList<>();
        for (int i=0;i<limit;i++) {
            CheckbedPageEncapsulation tmp = new CheckbedPageEncapsulation();
            tmp.RoomId = bed.get(i).getRoomNumber();
            tmp.BedNumber = bed.get(i).getBedNumber();
            tmp.remarks = bed.get(i).getBedStatus();
            if(customer.get(i)==null){
                tmp.number=null;
                tmp.name=null;
                tmp.sex=null;
            }
            else {
                tmp.number = customer.get(i).getArchivesid();
                tmp.name = customer.get(i).getName();
                tmp.sex = customer.get(i).getSex();
            }
            if(bedRecord.get(i).getId()==null){
                tmp.start_time=null;
                tmp.end_time=null;
            }
            else {
                tmp.start_time = sdf.format(bedRecord.get(i).getOccupiedTime());
                if(bedRecord.get(i).getLeavingTime()==null)
                    tmp.end_time=null;
                else
                    tmp.end_time = sdf.format(bedRecord.get(i).getLeavingTime());
            }
            encapsulation.add(i, tmp);
        }
        return encapsulation;
    }


    //获取当前床的所有信息
    @RequestMapping(value = "checkbed_page/getDetail",method = RequestMethod.POST)
    public @ResponseBody String getDetail(String bedId)throws ParseException {
        Customer customer = customerMapper.selectByBedId(Integer.parseInt(bedId));
        if(customer == null){
            return new JsonResult(false,"该床没有住人").toString();
        }else {
            DetailList detailList = new DetailList(customer.getId(), customer.getName(), customer.getAge(), customer.getSex(), customer.getIdNumber(),
                    customer.getArchivesid(), customer.getPhoneNumber(), customer.getHeight(), customer.getMaritalStatus(),
                    customer.getWeight(), customer.getBloodType(), customer.getNursingLevel());
            return new JsonResult(true,detailList).toString();
        }
    }

    @RequestMapping(value = "checkbed_page/getBed",method = RequestMethod.POST)
    public @ResponseBody
    String getBedByFloor(String floor, String building, int page){
        int data_per_page = 6;
        int total_data_no = bedMapper.countByFloorPosition(floor,building);
        if(total_data_no<=0)
            return new JsonResult(false, new CheckbedPageEncapsulation2()).toString();

        int offset=(page-1)*data_per_page;
        int limit;
        if(total_data_no-offset<data_per_page)
            limit=total_data_no-offset;
        else
            limit=data_per_page;
        if(total_data_no<=offset)
            return new JsonResult(false, "页数过大，数据不够").toString();

        List<Bed> bed = bedMapper.selectByLimitOffsetFloorPosition(limit,offset,floor,building);

        List<Customer> customer = search_customer_by_bed(bed);
        if (customer.size() != bed.size())
            return new JsonResult(false, "未查找到部分床的老人").toString();

        List<BedRecord> bedRecord = search_bed_record_by_bed_customer(bed,customer);
        if (bedRecord.size() != bed.size())
            return new JsonResult(false, "未查找到部分床的记录").toString();

        CheckbedPageEncapsulation2 total_data=new CheckbedPageEncapsulation2();
        List<CheckbedPageEncapsulation> Encapsulation = getEncapsulation(bed,customer,bedRecord,limit);
        total_data.bed_list=Encapsulation;
        total_data.total_page=(total_data_no-1)/data_per_page+1;

        return new JsonResult(true, total_data).toString();
    }
}

